# coding=utf-8
__author__ = 'liubin'

from decimal import Decimal
from datetime import datetime
from tornado.web import authenticated, asynchronous
from sqlalchemy import or_, desc, and_
from sqlalchemy.orm import joinedload, contains_eager
from tornado_json.requesthandlers import APIHandler
from project.tools import HandlerMixin, unblock, to_json
from project.tools.constants import PurchaseOrderType
from project.models import PurchaseOrder, PurchaseOrderDetail, supplier


class PurchaseOrderDetailHandler(HandlerMixin, APIHandler):
    """
    供应商API
    """
    __url_names__ = []

    @asynchronous
    def check_id_exist(self, id):
        """
        检查ID存在
        """
        record = self.db_conn.query(PurchaseOrderDetail).join(PurchaseOrderDetail.order)\
            .options(contains_eager(PurchaseOrderDetail.order)).filter(
            and_(
                PurchaseOrderDetail.id == id,
                PurchaseOrder.status != PurchaseOrderType.deleted.value,
                PurchaseOrderDetail.status != PurchaseOrderType.deleted.value
            )
        ).first()
        if not record:
            self.error(u'指定原料厂不存在')
        return record


class SingleHandler(PurchaseOrderDetailHandler):
    """
    单条记录处理
    """
    __urls__ = [r"/api/purchaseOrder/(?P<oid>[a-zA-Z0-9_]+)/detail/(?P<did>[a-zA-Z0-9_]+)/?"]

    @authenticated
    @unblock
    def get(self, oid, did):
        """
        获得单条记录
        :param id:
        :return:
        """
        print('did', did)
        record = self.check_id_exist(did)
        if record:
            # # 结合查询，多表结合要分段写
            # record = self.db_conn.query(PurchaseOrder).join(PurchaseOrder.detail, PurchaseOrderDetail.category).join(
            #     PurchaseOrder.detail, PurchaseOrderDetail.color).options(
            #     contains_eager(PurchaseOrder.detail, PurchaseOrderDetail.category)).options(
            #     contains_eager(PurchaseOrder.detail, PurchaseOrderDetail.color)).filter(
            #     and_(
            #         PurchaseOrder.id == id,
            #         PurchaseOrder.status != PurchaseOrderType.deleted.value
            #     )
            # ).first()
            self.success(to_json(record))

    @authenticated
    @unblock
    def put(self, oid, did):
        """
        更新单条记录
        :param id:
        :return:
        """
        record = self.check_id_exist(did)
        if record:
            data = self.json_args
            # supplier.name = data.get('name')
            # supplier.address = data.get('address')
            record.price = data.get('price')
            record.count = data.get('count')
            record.amount = Decimal(record.price) * Decimal(record.count)
            record.comment = data.get('comment')
            self.db_conn.commit()
            self.success(None)

    @authenticated
    @unblock
    def delete(self, oid, did):
        """
        删除
        """
        record = self.check_id_exist(did)
        print(record)
        if record:
            record.status = PurchaseOrderType.deleted.value
            print(record.status)
            self.db_conn.commit()
            self.success(None)


class ListHandler(PurchaseOrderDetailHandler):
    """
    记录列表
    """
    __urls__ = [r'/api/purchaseOrder/(?P<oid>[a-zA-Z0-9_]+)/detail/?']

    @authenticated
    @unblock
    def post(self, oid):
        """
        新增
        :return:
        """
        json = self.json_args;
        record = PurchaseOrderDetail(json)
        record.orderId = oid
        record.amount = Decimal(record.price) * Decimal(record.count)
        self.db_conn.add(record)
        self.db_conn.commit()
        self.success(None)
